package com.cskaoyan.servlet;

import com.cskaoyan.bean.MarketIssue;
import com.cskaoyan.bean.common.BaseRespVo;
import com.cskaoyan.bean.common.CommonData;
import com.cskaoyan.service.IssueService;
import com.cskaoyan.service.IssueServiceImpl;
import com.cskaoyan.util.JacksonUtil;
import com.cskaoyan.util.ResponseUtil;
import com.cskaoyan.util.StringUtil;
import lombok.SneakyThrows;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@WebServlet("/admin/issue/*")
public class AdminIssueServlet extends WdBaseServlet {

    IssueService issueService = new IssueServiceImpl();

    //  /admin/issue/list
    /*
     http://101.43.69.31:8083/admin/issue/list?page=1&limit=20&sort=add_time&order=desc
     */
    @SneakyThrows
    private void list(HttpServletRequest req, HttpServletResponse response) {
        Integer page = StringUtil.isNotEmpty(req.getParameter("page")) ? Integer.parseInt(req.getParameter("page")) : null;
        Integer limit = StringUtil.isNotEmpty(req.getParameter("limit")) ? Integer.parseInt(req.getParameter("limit")) : null;
        String sort = req.getParameter("sort");
        String order = req.getParameter("order");
        String question = StringUtil.isEmpty(req.getParameter("question")) ? null : req.getParameter("question");

        List<MarketIssue> issueList = issueService.query(question, page, limit, sort, order);
        ResponseUtil.responseOkJsonVo(response, CommonData.data(issueList));
    }

    //  /admin/issue/create
    private void create(HttpServletRequest req, HttpServletResponse response) throws IOException {
        String jsonStr = req.getReader().readLine();
        MarketIssue issue = JacksonUtil.read(jsonStr, MarketIssue.class);
        BaseRespVo create = issueService.create(issue);
        ResponseUtil.responseJson(response, create);
    }

    //  /admin/issue/update
    private void update(HttpServletRequest req, HttpServletResponse response) throws IOException {
        String jsonStr = req.getReader().readLine();
        MarketIssue issue = JacksonUtil.read(jsonStr, MarketIssue.class);
        BaseRespVo update = issueService.update(issue);
        ResponseUtil.responseJson(response, update);
    }

    //  /admin/issue/delete
    private void delete(HttpServletRequest req, HttpServletResponse response) throws IOException {
        String jsonStr = req.getReader().readLine();
        MarketIssue issue = JacksonUtil.read(jsonStr, MarketIssue.class);
        BaseRespVo remove = issueService.remove(issue);
        ResponseUtil.responseJson(response, remove);
    }
}
